/* ============== Mongodb ============== */

// ============== Socket.IO && NodeJS Web Server ==============
var app = require('express')();
var http = require('http').Server(app);
// plug socket io to nodejs web server
var io = require('socket.io')(http);
var assert = require('assert');
var fs = require('fs');
eval(fs.readFileSync('dp.js')+'');

app.get('/', function(req, res){
	//res.send('<h1>Hello World </h1>');
	res.sendFile( __dirname + '/index.html');
});

io.on('connection',function(socket){
	console.log('a user connected');
	
	socket.on('disconnect',function(){
		console.log('user disconnected');
	});
	socket.on('connectdb',function(msg){
		console.log(msg);
		connectTest1(function(result){
			// suppose status is diff
			var msg = result.msg; // have to declare msg
			if(result.status){				
				io.emit('connectdb', msg);
			}
			else{
				io.emit('connectdb', msg);
			}
		});
	});
	socket.on('insert',function(msg){
		var data = {id:111, username:'phong', password:'123456'};
		
		//insertDocuments(); // ok
		//insert1('users', data); // ok
		
		insert('users', data, function(result){
			//var msg = JSON.stringify(result);
			io.emit('insert', result);
		});
	});
	
	socket.on('update', function(msg){
		var query = msg[0];
		var update = msg[1];
		updateUser('users', query, update, function(result){
			io.emit('update', result);
		});	
	});
	socket.on('get', function(query){		
		viewDocuments('users', query, function(result){
			io.emit('get', result);
		});	
	});
	socket.on('delete', function(query){		
		deleteUser('users', query, function(result){
			io.emit('delete', result);
		});	
	});
	
});

http.listen(8080, function(){
	console.log('listening on *:8080')
});